package com.example.mall.mq;

import com.alibaba.fastjson.JSON;
import com.example.mall.constants.BaseConstants;
import com.example.mall.dto.SMSSend2MQ;
import com.example.mall.exception.ErrorEnumCode;
import com.example.mall.exception.GlobalCustomerException;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;

/**
 * @Author: xxxliu
 * @CreateTime: 2025-05-14
 * @Version: 1.0
 */
@Component
@RocketMQMessageListener(consumerGroup = "service-common-smsmessage-consumer",
        topic = BaseConstants.MessageMQ.TOPIC_MESSAGE,
        selectorExpression = BaseConstants.MessageMQ.TAGS_SMS_NAME
)
@Slf4j
public class SMSMessageMQConsumer implements RocketMQListener<MessageExt> {


    // todo 短信发送 如表操作

    @Override
    public void onMessage(MessageExt message) {
        try {
            String bodyStr = new String(message.getBody(),"utf-8");
            SMSSend2MQ smsSend2MQ = JSON.parseObject(bodyStr, SMSSend2MQ.class);
            //用户群发
            if(smsSend2MQ.getUserIds() != null && !smsSend2MQ.getUserIds().isEmpty()){
                smsSend2MQ.getUserIds().forEach(userId->{
//                    saveMessage2db(smsSend2MQ,userId);
                    log.info("短信发送：{}，{}",userId,smsSend2MQ.getContent());
                });
            }else{
//                saveMessage2db(smsSend2MQ,null);
                log.info("短信发送：{}，{}",null,smsSend2MQ.getContent());
            }


        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            //通过异常来决定ACK
            throw new GlobalCustomerException(ErrorEnumCode.SMS_SENDING_FAILED);
        }
    }

//    public void saveMessage2db(SMSSend2MQ smsSendVO,Long userId){
//        MessageSms messageSms = new MessageSms();
//        messageSms.setContent(smsSendVO.getContent());
//        messageSms.setSendTime(new Date());
//        messageSms.setTitle(smsSendVO.getTitle());
//        messageSms.setUserId(userId);
//        messageSmsService.insert(messageSms);
//    }
}
